package clsr.info.blog.web.controller;

import clsr.info.blog.common.api.IArticleService;
import clsr.info.blog.common.entity.Article;
import clsr.info.blog.common.entity.Classify;
import clsr.info.blog.common.pojo.JsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/article")
public class ArticleController {
  @Autowired private IArticleService articleService;

  @RequestMapping("/save")
  public JsonResponse<Integer> saveArticle(@RequestBody Article article) {
    article.setCreateTime(new Date());
    article.setCreateUserId(1);
    article.setStatus(0);
    Integer id = articleService.saveArticle(article);
    return JsonResponse.success(id);
  }

  @RequestMapping("/loadArticle")
  public JsonResponse<Article> loadArticle(Integer id) {
    Article article = articleService.loadArticle(id);
    return JsonResponse.success(article);
  }

  @RequestMapping("/loadArticleList")
  public JsonResponse<Page<Article>> loadArticleList(
      Integer classifyId, Integer pageNum, String orderBy) {
    Sort sort = Sort.by(Sort.Order.desc(orderBy));
    Pageable pageable = PageRequest.of(pageNum, 10, sort);
    Article article = new Article();
    article.setCreateUserId(1);
    article.setStatus(0);
    article.setPublishStatus(1);
    if (classifyId != null) {
      Classify classify = new Classify();
      classify.setId(classifyId);
      article.setClassify(classify);
    }
    Page<Article> page = articleService.loadArticleList(article, pageable);
    return JsonResponse.success(page);
  }
}
